package socket

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"socket/common"
	"socket/controller/user"
	"strconv"
	"sync"
)

type Client struct {
	ID        int
	WebSocket *websocket.Conn
}

var clients = make(map[int]*Client)
var mu sync.RWMutex // 用于保护并发访问 clients 映射

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
		// 解决跨域问题
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

func Socket(c *gin.Context) {
	userId, _ := strconv.Atoi(c.DefaultQuery("user_id", "0"))
	//types, _ := strconv.Atoi(c.DefaultQuery("type", "0"))
	//positionId, _ := strconv.Atoi(c.DefaultQuery("position_id", "0"))

	DB := common.GetDB()
	var userList user.UserJson
	DB.Where("id = ?", userId).Find(&userList)
	//fmt.Println(types)
	//fmt.Println(positionId)

	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println("连接失败" + err.Error())
		//ws.Close()
		return
	}

	client := &Client{
		ID:        userId,
		WebSocket: ws,
	}
	mu.Lock()
	clients[client.ID] = client // 将客户端添加到全局map中
	mu.Unlock()
	defer func() {
		mu.Lock()
		delete(clients, userId)
		mu.Unlock()
	}()

	for {

		// Read 接收消息
		messageType, msg, err := ws.ReadMessage()
		if messageType == -1 { //断开连接直接返回
			return
		}
		if err != nil {
			fmt.Println("Read 接收消息失败" + err.Error())
			return
		}

		fmt.Println("111111111111")
		fmt.Println(msg)
		fmt.Println(string(msg))
		fmt.Println(clients)
		fmt.Println("222222222222")

		datas := map[string]interface{}{
			"user_id":   userId,
			"user_name": userList.Username,
			"avatar":    userList.Avatar,
			"msg":       string(msg),
		}

		// 将map转换为JSON格式
		jsonData, err := json.Marshal(datas)
		if err != nil {
			fmt.Println("转换为JSON时出错：", err)
			return
		}

		//newData := append(byteUserId, msg...)
		fmt.Println("555555555555")
		fmt.Println(string(jsonData))
		fmt.Println("66666666666666666")

		if string(msg) != "ping" { //心跳检测
			//write发送消息到客户端
			for i := range clients {
				err = clients[i].WebSocket.WriteMessage(messageType, jsonData)
				if err != nil {
					return
				}
			}
		}

	}
}
